<?php


namespace app\api\logic;


use app\model\pms\Goods;
use app\model\pms\GoodsBrowse;
use app\model\pms\GoodsCate;
use support\constants\RedisKey;
use support\Redis;
use support\utils\ArrayUtil;
use support\utils\Form;
use support\utils\Time;
use think\db\Query;
use think\facade\Db;

class GoodsLogic extends \app\admin\pms\logic\GoodsLogic
{


    public function search(array $searchWhere = [])
    {
        return $this->model
            ->where([
                ['is_del', '=', 0],
                ['is_show', '=', 1],
            ])->where($searchWhere);
    }

    public function goodsPage(Form $form)
    {
        $where = [];
        $order = [
            'create_time' => "desc"
        ];

        $form['search'] && $where[] = ['name', 'like', "%{$form['search']}%"];
        $form['cate_id1'] && $where[] = ['cate_id1', '=', $form['cate_id1']];
        $form['cate_id2'] && $where[] = ['cate_id2', '=', $form['cate_id2']];
        $form['cate_id3'] && $where[] = ['cate_id3', '=', $form['cate_id3']];

        if ($form['sortfield'] && $form['order']) {
            $order = [
                $form['sortfield'] => $form['order']
            ];
        }

        if ($form['search']) {
            //增加搜索记录
            Redis::zIncrBy(RedisKey::SEARCH_KEYWORD_KEY, 1, $form['search']);
        }

        $query = $this->search($where);
        $query->order($order);
        $query->field('*');
        $query->order($form->getSortField(), $form->getOrder());
        $query->with(array_merge([
            "brand" => function (Query $query) {
                $query->field(['id', 'name']);
            },
        ], Goods::getCateWith()));
        $data = $this->paginate($query, $form->getPage(), $form->getPageSize());
        return $data;
    }

    public function goodsDetail($id)
    {
        $where = [
            'id' => $id
        ];
        $query = $this->search($where);
        $query->with(array_merge([
            "goodsspec",
            "goodssku",
        ], Goods::getCateWith()));
        $data = $query->find()->toArray();
        if ($data) {
            $data['is_collect'] = $this->isCollect($data['id']);
        }
        return $data;
    }

    public function recommendCateGoods()
    {
        $cate = GoodsCate::where([
            'status' => 1,
            "is_recommend" => 1,
            'pid' => 0
        ])->field([
            "id",
            "name",
            "big_pic",
        ])->select()->toArray();

        $sqlS = [];
        foreach ($cate as $value) {
            $query = $this->search([
                'cate_id1' => $value['id']
            ]);
            $sqlS[] = "(" . $query->limit(10)->field([
                    'id',
                    'name',
                    'cate_id1',
                    'min_price',
                    'main_image',
                ])->order("create_time desc")->fetchSql()->select() . ")";
        }
        $data = Db::query(implode(" union all ", $sqlS));

        $data = ArrayUtil::group($data, 'cate_id1');
        foreach ($cate as $key => $v) {
            if (isset($data[$v['id']])) {
                $cate[$key]['goodsList'] = $data[$v['id']];
            } else {
                unset($cate[$key]);
            }
        }
        return array_values($cate);
    }

    public function homeGoods()
    {
        $where = [
            ['is_hot|is_recommend|is_new', '=', 1]
        ];
        $query = $this->search($where);
        $data = $query->limit(10)->field([
            'id',
            'name',
            'min_price',
            'main_image',
        ])->order("create_time desc")->select()->toArray();
        if (!$data) {
            $where = [];
            $query = $this->search($where);
            $data = $query->limit(10)->field([
                'id',
                'name',
                'min_price',
                'main_image',
            ])->order("create_time desc")->select()->toArray();
        }
        return $data;
    }

    public function searchPageGoods()
    {
        $where = [
            ['is_hot|is_recommend|is_new', '=', 1]
        ];
        $query = $this->search($where);
        $data = $query->limit(6)->field([
            'id',
            'name',
            'min_price',
            'main_image',
        ])->order("create_time desc")->select()->toArray();
        return $data;
    }

    /**
     * 热门搜索关键词
     * @return array
     */
    public function hotSearchKeyword()
    {
        $res = Redis::zrevrange(RedisKey::SEARCH_KEYWORD_KEY, 0, 9);
        if ($res) {
            return array_map(function ($v) {
                return [
                    'name' => $v,
                ];
            }, $res);
        }
        return [
            [
                "name" => '卫衣',
            ],
            [
                "name" => '外套',
            ],
            [
                "name" => '毛衣',
            ],
            [
                "name" => '马甲',
            ],
            [
                "name" => '牛仔裤',
            ],
            [
                "name" => '套装',
            ],
            [
                "name" => '连衣裙',
            ],
        ];
    }

    public function addGoodsBrowse($goods_id)
    {
        if (!$goods_id) {
            return;
        }
        $count = GoodsBrowse::where([
            'user_id' => request()->uid,
            'goods_id' => $goods_id,
        ])->count();
        if ($count <= 0) {
            GoodsBrowse::insert([
                'user_id' => request()->uid,
                'goods_id' => $goods_id,
                'create_time' => Time::now(),
            ]);
        }

        Goods::where(['id' => $goods_id])->update([
            'views' => Db::raw('views+1')
        ]);
    }

    public function unCollectGoods($goods_id)
    {
        GoodsBrowse::where([
            'user_id' => request()->uid,
            'goods_id' => $goods_id,
        ])->delete();
    }

    public function collectGoods($goods_id)
    {
        $count = GoodsBrowse::where([
            'user_id' => request()->uid,
            'goods_id' => $goods_id,
        ])->count();
        if ($count <= 0) {
            GoodsBrowse::insert([
                'user_id' => request()->uid,
                'goods_id' => $goods_id,
                'create_time' => Time::now(),
            ]);
        }

    }

    public function isCollect($goods_id)
    {
        $count = GoodsBrowse::where([
            'user_id' => request()->uid,
            'goods_id' => $goods_id,
        ])->count();
        return $count > 0;
    }
}